package ncs.common.util;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import ncs.common.model.SessionStore;

import org.apache.struts2.ServletActionContext;

public class Util {
	/**
	 * 在上传目录下获取唯一文件名为防止上传文件名重复
	 * @param path	文件保存目录
	 * @param fileName	文件名
	 * @return 返回唯一文件名
	 */
	public static String getUniqueName(String path,String fileName)
	{
		File f=new File(path+"\\"+fileName);
		if(!f.exists())
			return fileName;
		int index=1;
		int extindex=fileName.lastIndexOf('.');
		if(extindex==-1)
			extindex=fileName.length();
		String name=fileName.substring(0, extindex);
		String ext=fileName.substring(extindex);
		while(true)
		{
			String copy=name+String.format("(%d)",index++);
			f=new File(String.format("%s\\%s%s",path,copy,ext));
			if(!f.exists())
				return copy+ext;
		}
	}
	public static SessionStore getSessionStore()
	{
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session=request.getSession();
		return (SessionStore)session.getAttribute("user");
	}
}
